package com.aigou.filter;

import com.aigou.exception.LoginException;
import com.aigou.pojo.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    HttpSession session;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (request.getSession().getAttribute("user") == null) {
            throw new LoginException("请登录");
        }

        // /goods/add   /goods/check   /user/findOne
        List<Menu> menus = (List<Menu>) request.getSession().getAttribute("userMenus");
        // /goods/check/2/1
        String servletPath = request.getServletPath();
        boolean flag = false;
        for (Menu menu : menus) {
            if (servletPath.startsWith(menu.getPath())) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            throw new LoginException("无权限");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
